package tool.lib.volley;


import android.util.Log;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;


import com.android.volley.AuthFailureError;
import com.android.volley.Cache;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.RetryPolicy;
import com.android.volley.toolbox.HttpHeaderParser;


public class JsonRequest extends Request<JSONObject>{
	private Response.Listener listener;
	private Map<String, String> map;
	public JsonRequest(String url, Response.Listener listener, Response.ErrorListener errorListener) {
		super(Method.POST, url,errorListener);
		// TODO Auto-generated constructor stub
        this.setRetryPolicy(new DefaultRetryPolicy(20000, 0 ,DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
		this.setShouldCache(false);
		this.listener=listener;
		this.map=new HashMap<String,String>();
	}
    public JsonRequest(int way,String url, Response.Listener listener, Response.ErrorListener errorListener){
        super(way,url,errorListener);
        this.setRetryPolicy(new DefaultRetryPolicy(20000, 0, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        this.setShouldCache(false);
        this.listener=listener;
    }
    public void put(String key,String value)
    {
        this.map.put(key,value);
    }

    public Map<String, String> getMap() {
        return map;
    }

    @Override
	protected void deliverResponse(JSONObject object) {
		// TODO Auto-generated method stub
		listener.onResponse(object);
	}

	@Override
	protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
		// TODO Auto-generated method stub
		try {
            String jsonString = new String(response.data,HttpHeaderParser.parseCharset(response.headers,"UTF-8"));
            Log.e("Request-string", jsonString);
            Cache.Entry entry=HttpHeaderParser.parseCacheHeaders(response);
            return Response.success(new JSONObject(jsonString),entry);
        } catch (UnsupportedEncodingException e) {
            return Response.error(new ParseError(e));
        } catch (JSONException je) {
            return Response.error(new ParseError(je));
        }
	}

	@Override
	protected Map<String, String> getParams() throws AuthFailureError {
        // TODO Auto-generated method stub
        return map;
    }
}
